package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.TreeNode;

import java.util.*;

/**
 * @Author fengye
 * @Date 2023/4/18 7:42
 **/
public class InvertBinaryTree226 {

    public TreeNode invert(TreeNode root) {
        if(root == null) {
            return null;
        }

        TreeNode left = root.left;
        root.left = root.right;
        root.right = left;

        invert(root.left);
        invert(root.right);
        return root;
    }

    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return root;
        }

        LinkedList<TreeNode> queue =  new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode currNode = queue.poll();
                TreeNode temp = currNode.left;
                currNode.left = currNode.right;
                currNode.right = temp;

                if (currNode.left != null) {
                    queue.offer(currNode.left);
                }

                if (currNode.right != null) {
                    queue.offer(currNode.right);
                }
            }
        }

        return root;
    }

}
